package com.sdleyou.treepro.common.service.impl;

import com.sdleyou.treepro.common.exception.ServiceException;
import com.sdleyou.treepro.common.model.dao.PetDO;
import com.sdleyou.treepro.common.model.dto.PetDTO;
import com.sdleyou.treepro.common.model.enums.ErrorCodeEnum;
import com.sdleyou.treepro.common.model.enums.MapShowEnum;
import com.sdleyou.treepro.common.model.utils.RandomUtil;
import com.sdleyou.treepro.common.service.PetManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class PetManagerImpl implements PetManager {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void createPet(PetDTO petDTO) {
        PetDO petDO = new PetDO();
        petDO.setPetId(RandomUtil.randomId());
        petDO.setPetName(petDTO.getPetName());
        petDO.setPetDesc(petDTO.getPetDesc());
        petDO.setPetIcon(petDTO.getPetIcon());
        petDO.setPetImage(petDTO.getPetImage());
        petDO.setWorkTime(petDTO.getWorkTime());
        petDO.setIsShow(MapShowEnum.HIDDEN.name());
        Date date = new Date();
        petDO.setGmtCreate(date.getTime());
        petDO.setGmtModified(date.getTime());
        mongoTemplate.insert(petDO);
        return;
    }

    @Override
    public void updatePet(PetDTO petDTO, String petId) {
        Query query = new Query(Criteria.where("pet_id").is(petId));
        PetDO petDO = mongoTemplate.findOne(query, PetDO.class);
        if (petDO == null) {
            throw new ServiceException(ErrorCodeEnum.E007.code(), "宠物信息不存在");
        }
        Update update = new Update();
        if (!StringUtils.isEmpty(petDTO.getPetName())) {
            update.set("pet_name", petDTO.getPetName());
        }
        if (!StringUtils.isEmpty(petDTO.getPetDesc())) {
            update.set("pet_desc", petDTO.getPetDesc());
        }
        if (!StringUtils.isEmpty(petDTO.getPetIcon())) {
            update.set("pet_icon", petDTO.getPetIcon());
        }
        if (!StringUtils.isEmpty(petDTO.getPetImage())) {
            update.set("pet_image", petDTO.getPetImage());
        }
        if (!StringUtils.isEmpty(petDTO.getWorkTime())) {
            update.set("work_time", petDTO.getWorkTime());
        }
        if (!StringUtils.isEmpty(petDTO.getIsShow())) {
            update.set("is_show", petDTO.getIsShow());
        }
        mongoTemplate.updateFirst(query, update, PetDO.class);
        return;
    }
}
